import emoji from './emoji.js'

const util = {
	
	/**
	 * @param {Object} nS
	 * 将时间戳转换成日期格式
	 */
	getLocalTime(nS) {  
		return new Date(parseInt(nS) * 1000).toLocaleString().replace(/:\d{1,2}$/,' ');  
	},
	
	/**
	 * 处理消息列表消息显示格式
	 */
	showMsg(msg){
		switch(msg.lastMessage[0].type){
			case 1: //文字
				msg.lastMessage[0].time = util.getDateDiff(msg.lastMessage[0].time * 1000)
				msg.lastMessage[0].content = util.parseText(msg.lastMessage[0].content)
				break
			case 2: // 图片
				msg.lastMessage[0].time = util.getDateDiff(msg.lastMessage[0].time * 1000)
				msg.lastMessage[0].content = "[图片]"
				break
		}
		return msg
	},
	
	/**
	 * 处理对话页面消息显示格式
	 */
	showC2C(msg){
		switch(msg.type){
			case "text": //文字
				msg.msg = util.parseText(msg.msg)
				break
		}
		return msg
	},
	
	/**
	 * @param {Object} text
	 * 解析文本表情消息
	 */
	parseText(text) {
	  let renderDom = ""
	  // 文本消息
	  let temp = text
	  let left = -1
	  let right = -1
	  while (temp !== '') {
	    left = temp.indexOf('[')
	    right = temp.indexOf(']')
	    switch (left) {
	      case 0:
	        if (right === -1) {
			  renderDom += temp
	          temp = ''
	        } else {
	          let _emoji = temp.slice(0, right + 1)
	          if (emoji.emojiMap[_emoji] != null) {    // 如果您需要渲染表情包，需要进行匹配您对应[呲牙]的表情包地址
				renderDom += " <image src=" + emoji.emotions[emoji.emojiMap[_emoji]][1] + " mode='aspectFill' style='width: 24px;height: 24px;margin-left: 5px'></image>"
	            temp = temp.substring(right + 1)
	          } else {
				renderDom += text
	            temp = temp.slice(1)
	          }
	        }
	        break
	      case -1:
			renderDom += temp
	        temp = ''
	        break
	      default:
			renderDom += temp.slice(0, left)
	        temp = temp.substring(left)
	        break
	    }
	  }
	  return renderDom
	},
	
	/**
	 * 时间戳转化为几天前，几小时前，几分钟前
	 * @param {Object} dateTimeStamp
	 */
	getDateDiff(dateTimeStamp) {
		let result;
		let minute = 1000 * 60;
		let hour = minute * 60;
		let day = hour * 24;
		let halfamonth = day * 15;
		let month = day * 30;
		let year = month * 12;
		let now = new Date().getTime();
		let diffValue = now - dateTimeStamp;
		
		if (diffValue < 0) { return; }
		
		let yearC = diffValue / year;
		let monthC = diffValue / month;
		let weekC = diffValue / (7 * day);
		let dayC = diffValue / day;
		let hourC = diffValue / hour;
		let minC = diffValue / minute;
		if (yearC >= 1) {
			result = "" + parseInt(yearC) + "年前";
		}else if (monthC >= 1) {
			result = "" + parseInt(monthC) + "月前";
		}
		else if (weekC >= 1) {
			result = "" + parseInt(weekC) + "周前";
		}
		else if (dayC >= 1) {
			result = "" + parseInt(dayC) + "天前";
		}
		else if (hourC >= 1) {
			result = "" + parseInt(hourC) + "小时前";
		}
		else if (minC >= 1) {
			result = "" + parseInt(minC) + "分钟前";
		} else{
			result = "刚刚";
		}
			
		return result;
	}
}

export default util